<?php

function follow($file)
{
    $size = 0;
	$line = 0;
    while (true) {
        clearstatcache();
        $currentSize = filesize($file);
        if ($size == $currentSize) {
            usleep(100);
            continue;
        }

        $fh = fopen($file, "r");
        fseek($fh, $size);
		$i=0;
		while ($d = fgets($fh)) {
           if($line == $i) break;
		   $i ++;
        }
		 echo "\r\n";
        while ($d = fgets($fh)) {
            echo $d;
			$line ++;
        }
        fclose($fh);
        $size = $currentSize;
    }
}
function read_file($file, $lines) {
    //global $fsize;
    $handle = fopen($file, "r");
    $linecounter = $lines;
    $pos = 2;
    $beginning = false;
    $text = array();
    while (true) {
        $t = " ";
        while ($t != "\n") {
            if(fseek($handle, $pos, SEEK_END) == -1) {
                $beginning = true; 
                break; 
            }
            $t = fgetc($handle);
            $pos ++;
        }
        $linecounter ++;
		echo fgets($handle);
        //$text[$lines-$linecounter-1] = fgets($handle);
        if ($beginning) break;
    }
    fclose ($handle);
    return array_reverse($text);
}

if(count($argv)==2) {
	$fsize = round(filesize($argv[1])/1024/1024,2); 
	echo "\nFile Name ::".$argv[1]."\n";
	echo "File size is {$fsize} megabytes\n\n";
	follow($argv[1]);
	//$lines = read_file($argv[1], 5);
	//foreach ($lines as $line) {
		//echo $line;
	//}
}else{
	echo "Run as php tail.php <file_name>\r\n"; 
}
?>